package edu.wayne.cs.csc4110.hw6.framework.gui.lobby;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import edu.wayne.cs.csc4110.hw6.framework.lobby.GameLobbyClient;
import edu.wayne.cs.csc4110.hw6.framework.message.LobbyMessage;

public class SendMessagesPanel extends JPanel {

	private JLabel userLabel;
	private JTextField messageTextField;
	private JButton sendBtn;
	private GameLobbyClient lobby;

	public SendMessagesPanel(GameLobbyClient gameLobbyClient) {
		lobby = gameLobbyClient;
		userLabel = new JLabel(lobby.getUser().getUsername());
		messageTextField = new JTextField(50);
		sendBtn = new GameButton("Send");

		add(userLabel);
		add(messageTextField);
		add(sendBtn);
		messageTextField.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyPressed(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					lobby.sendMessage(createMessage());
					messageTextField.setText("");
				}
			}

		});
		sendBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (!messageTextField.getText().equals("")) {
					lobby.sendMessage(createMessage());
					messageTextField.setText("");
					messageTextField.requestFocus();
				}
			}
		});

	}

	private LobbyMessage createMessage() {
		return new LobbyMessage(lobby.getUser(), messageTextField.getText());
	}
}
